/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.modbusServer.api;

import com.ghgande.j2mod.modbus.ModbusCoupler;
import com.ghgande.j2mod.modbus.net.AbstractModbusListener;
import com.ghgande.j2mod.modbus.procimg.ProcessImage;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage;
import com.ghgande.j2mod.modbus.procimg.SimpleRegister;
import com.seari.modbusServer.SEmodbusListenerFactory;
import static com.seari.modbusServer.api.SimpleModbusServerApiImpl.logger;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class CommonModbusServerApiImpl implements IModbusServerApi
{

    protected static Logger logger = LoggerFactory.getLogger(CommonModbusServerApiImpl.class);

    @Override
    public void createServer(int unitID, int port, int poolSize, int regCount)
    {
        AbstractModbusListener listener = null;
        SimpleProcessImage spi;
        String connString = "tcp:127.0.0.1" + ":" + port;
        spi = new SimpleProcessImage(unitID);
        for (int i = 0; i < regCount; i++)
        {
            spi.addRegister(i, new SimpleRegister(0));
        }
        ModbusCoupler.getReference().setProcessImage(spi);
        ModbusCoupler.getReference().setMaster(false);
        try
        {
            listener = SEmodbusListenerFactory.createModbusListener(connString, poolSize);
            logger.info("server start at {} and poolSize is {}", port, poolSize);
        } catch (Exception ex)
        {
            logger.warn(ex.getMessage());
        }
    }

    //添加startListen参数，为FALSE时将不进行端口监听
    public void createServer(int unitID, int port, int poolSize, int regCount, boolean startListen)
    {
        AbstractModbusListener listener = null;
        SimpleProcessImage spi;
        String connString = "tcp:127.0.0.1" + ":" + port;
        spi = new SimpleProcessImage(unitID);
        for (int i = 0; i < regCount; i++)
        {
            spi.addRegister(i, new SimpleRegister(0));
        }
        ModbusCoupler.getReference().setProcessImage(spi);
        ModbusCoupler.getReference().setMaster(false);
        if (startListen)
        {
            try
            {
                listener = SEmodbusListenerFactory.createModbusListener(connString, poolSize);
                logger.info("server start at {} and poolSize is {}", port, poolSize);
            } catch (Exception ex)
            {
                logger.warn(ex.getMessage());
            }
        }
    }

    //手动启动监听，配合createServer（含startListen）方法使用
    public void listenerStart(int port, int poolSize)
    {
        AbstractModbusListener listener = null;
        String connString = "tcp:127.0.0.1" + ":" + port;
        try
        {
            listener = SEmodbusListenerFactory.createModbusListener(connString, poolSize);
            logger.info("server start at {} and poolSize is {}", port, poolSize);
        } catch (Exception ex)
        {
            logger.warn(ex.getMessage());
        }
    }

    @Override
    public void refreshRegister(List<Map> emcsList)
    {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
             * 刷新默认UNIT （UNITID为1）中的寄存器值
     */
    @Override
    public void refreshRegister(int position, int value)
    {
        ProcessImage pi = ModbusCoupler.getReference().getProcessImage(1);
        Register register = pi.getRegister(position);
        register.setValue(value);
    }

	/**
	 * 刷新指定UNID中的寄存器值
	 */
	@Override
	public void refreshRegister(int unitID, int position, int value)
	{
		// TODO Auto-generated method stub
		ProcessImage pi = ModbusCoupler.getReference().getProcessImage(unitID);
        Register register = pi.getRegister(position);
        register.setValue(value);
	}

}
